package com.runtime.hongyunmanage.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.runtime.hongyunmanage.bean.*;
import com.runtime.hongyunmanage.mapper.ProductMapper;
import com.runtime.hongyunmanage.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Products> implements ProductService {

    @Autowired
    private ProductMapper productsMapper;

    //上架
    @Override
    @Transactional
    public void publishProduct(Integer productId) {
        productsMapper.publishProduct(productId);
    }

    //下架
    @Override
    @Transactional
    public void unpublishProduct(Integer productId) {
        productsMapper.unpublishProduct(productId);
    }


    @Override
    @Transactional
    public void editProductBasicInfo(Products product) {
        productsMapper.updateProductBasicInfo(product);
    }

    @Override
    @Transactional
    public void editProductDetailInfo( Productdetails details, List<ProductImage> images) {
        productsMapper.updateProductDetailInfo(details);
        productsMapper.addProductImages(details.getProductId(), images);

    }

    @Override
    public List<Products> findProcutsByCondition(int pageSize, int offset, Products products) {
        return productsMapper.findProductByCondition(pageSize, offset, products);
    }

    @Override
    public void updateProduct(Long productId, ProductRequest request) {
        // 更新商品基础信息
        Products product = request.getProduct();
        if (product != null) {
            product.setProductId(productId);
            productsMapper.updateProductBasicInfo(product);
        }

        // 更新商品详情信息
        Productdetails details = request.getDetails();
        if (details != null) {
            details.setProductId(productId);
            productsMapper.updateProductDetailInfo(details);
        }

        // 处理图片变更
        // 处理图片变更
        List<ProductImage> incomingImages = request.getImages();
        if (incomingImages != null) {
            // 查询数据库中现有图片
            List<ProductImage> dbImages = productsMapper.getImagesByProductId(productId);

            // 打印数据库查询返回的图片列表
            System.out.println("数据库查询返回的图片列表: " + dbImages);

            // 构建imageId到Image的映射
            Map<Long, ProductImage> dbImageMap = dbImages.stream()
                    .collect(Collectors.toMap(ProductImage::getImageId, img -> img, (existing, replacement) -> replacement));

            // 打印构建后的dbImageMap
            System.out.println("构建后的dbImageMap: " + dbImageMap);

            // 构建前端传入图片的imageId集合
            Set<Long> incomingImageIds = incomingImages.stream()
                    .filter(img -> img.getImageId() != null)
                    .map(ProductImage::getImageId)
                    .collect(Collectors.toSet());

            // 找出需要删除的图片
            List<Long> deletedImageIds = dbImages.stream()
                    .filter(img ->!incomingImageIds.contains(img.getImageId()))
                    .map(ProductImage::getImageId)
                    .collect(Collectors.toList());

            // 找出新增的图片
            List<ProductImage> newImages = incomingImages.stream()
                    .filter(img -> img.getImageId() == null)
                    .collect(Collectors.toList());

            // 找出需要更新排序的图片
            List<ProductImage> updatedImages = incomingImages.stream()
                    .filter(img -> {
                        if (img.getImageId() == null ||!dbImageMap.containsKey(img.getImageId())) {
                            return false;
                        }

                        ProductImage dbImage = dbImageMap.get(img.getImageId());
                        Integer dbSortOrder = dbImage.getSortOrder();
                        Integer incomingSortOrder = img.getSortOrder();

                        // 打印对比信息
                        boolean needUpdate =!Objects.equals(dbSortOrder, incomingSortOrder);
                        System.out.printf(
                                "图片ID=%d | 数据库排序=%s | 请求排序=%s | 是否需要更新=%b%n",
                                img.getImageId(),
                                dbSortOrder,
                                incomingSortOrder,
                                needUpdate
                        );

                        return needUpdate;
                    })
                    .collect(Collectors.toList());

            System.out.println("筛选前 - 所有传入图片: " + incomingImages);
            System.out.println("筛选后 - 需要更新排序的图片: " + updatedImages);

            // 执行数据库操作
            if (!deletedImageIds.isEmpty()) {
                productsMapper.deleteImages(deletedImageIds);
            }

            if (!newImages.isEmpty()) {
                newImages.forEach(img -> img.setProductId(productId));
                productsMapper.insertNewImages(newImages);
            }

            if (!updatedImages.isEmpty()) {
                productsMapper.updateImageSortOrder(updatedImages);
            }

        }
    }


    @Override
    public Map<String, Object> findProductsByCondition(int pageSize, int offset, Products products) {
        List<Products> list = productsMapper.findProductsWithDetails(pageSize, offset, products);
        int totals = productsMapper.CountProducts(products);

        Map<String, Object> result = new HashMap<>();
        result.put("list", list);
        result.put("totals", totals);
        return result;
    }

    @Override
    public int CountProducts(Products products) {
        return productsMapper.CountProducts(products);
    }

//    @Override
//    public List<Products> findProductsWithDetailsAndImages() {
//        return productsMapper.findProductsWithDetailsAndImages();
//    }

    @Override
    public void checkStockAlert() {
        List<Products> products = productsMapper.checkStockAlert();
        products.forEach(product ->
                System.out.println("库存预警：商品ID " + product.getProductId() + " 库存不足")
        );
    }

    @Override
    public Products findProductById(Integer productId) {
        return productsMapper.findProductById(productId);
    }

    @Override
    public Products findProductByNumber(String productNumber) {
        return productsMapper.findProductByNumber(productNumber);
    }

    @Override
    public List<Products> findProductsByName(String productName) {
        return productsMapper.findProductsByName(productName);
    }

    @Override
    public List<Products> findProductsByCategory(Integer categoryId) {
        return productsMapper.findProductsByCategory(categoryId);
    }

    @Override
    @Transactional
    public void addProduct(Products product, Productdetails details, List<ProductImage> images) {
        // 插入基础信息
        productsMapper.addProductBaseInfo(product);
        Long productId = product.getProductId();

        // 插入详细信息
        details.setProductId(productId);
        productsMapper.addProductDetailInfo(details);

        // 插入图片信息
        if (images != null && !images.isEmpty()) {
            productsMapper.addProductImages(productId, images);
        }
    }

    @Override
    @Transactional
    public void deleteProduct(Integer productId) {
        productsMapper.deleteProductImages(productId);
        productsMapper.deleteProductDetails(productId);
        productsMapper.deleteProductBaseInfo(productId);
    }
}